package com.ccys.cms.service.inventory.impl;

import cn.hutool.core.util.IdUtil;
import com.ccys.cms.service.inventory.InventoryFeedService;
import com.ccys.cms.service.inventory.PurchaseOrderDetailService;
import com.ccys.cms.service.inventory.PurchaseOrderService;
import com.ccys.common.vo.ResponseResult;
import com.ccys.db.dto.web.inventory.*;
import com.ccys.db.entity.TblInventoryFeed;
import com.ccys.db.entity.TblPurchaseOrder;
import com.ccys.db.entity.TblPurchaseOrderDetail;
import com.ccys.db.mapper.TblPurchaseOrderMapper;
import com.ccys.db.page.PageDto;
import com.ccys.db.rely.service.impl.BaseServiceImpl;
import com.ccys.db.vo.web.inventory.InventoryFlowVo;
import com.ccys.db.vo.web.inventory.InventoryListVo;
import com.ccys.db.vo.web.inventory.ProductBatchVo;
import com.ccys.db.vo.web.inventory.PurchaseOrderVo;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;
import java.util.stream.Collectors;


@Service
@Slf4j
public class PurchaseOrderServiceImpl extends BaseServiceImpl<TblPurchaseOrder> implements PurchaseOrderService {

    @Resource
    private TblPurchaseOrderMapper mapper;

    @Resource
    private InventoryFeedService feedService;

    @Resource
    private PurchaseOrderDetailService detailService;


    @Override
    public ResponseResult getPage(PurchaseOrderPageDto dto) {
        //根据当前用户groupid
        //超级管理员的区分 (超级管理员没有groupId 不会进查询条件)
        if (StringUtils.isEmpty(dto.getGroupId())) {
            String groupId = dto.getGroupId();
            dto.setGroupId(groupId);
        }
        PageDto.startPage();
        List<PurchaseOrderVo> list = mapper.getList(dto);
        PageInfo<PurchaseOrderVo> info = new PageInfo<>(list);
        return ResponseResult.success(info);
    }

    @Override
    public void deleteDetail(String orderId) {
        mapper.deleteDetail(orderId);
    }

    @Override
    public ResponseResult getInventoryPage(InventoryListDto dto) {

        //根据当前用户groupid
        //超级管理员的区分 (超级管理员没有groupId 不会进查询条件)
        if (StringUtils.isEmpty(dto.getGroupId())) {
            String groupId = dto.getGroupId();
            dto.setGroupId(groupId);
        }
        PageDto.startPage();
        List<InventoryListVo> list = mapper.getInventoryList(dto);
        PageInfo<InventoryListVo> info = new PageInfo<>(list);
        return ResponseResult.success(info);
    }

    @Override
    public ResponseResult getProductBatch(ProductBatchDto dto) {

        PageDto.startPage();
        List<ProductBatchVo> list = mapper.getProductBatch(dto);
        PageInfo<ProductBatchVo> info = new PageInfo<>(list);
        return ResponseResult.success(info);
    }

    @Override
    public ResponseResult getInventoryFlow(InventoryFlowDto dto) {

        //根据当前用户groupid
        //超级管理员的区分 (超级管理员没有groupId 不会进查询条件)
        if (StringUtils.isEmpty(dto.getGroupId())) {
            String groupId = dto.getGroupId();
            dto.setGroupId(groupId);
        }

        PageDto.startPage();
        List<InventoryFlowVo> list = mapper.getInventoryFlow(dto);
        PageInfo<InventoryFlowVo> info = new PageInfo<>(list);
        return ResponseResult.success(info);
    }

    @Override
    public ResponseResult change(PurchaseOrderDto dto) {


        TblPurchaseOrder order = dto.getOrder();
        //采购单类型 Purchase:采购单;Exchange:退换货单
        order.setType("Purchase");
        List<TblPurchaseOrderDetail> detailList = dto.getDetailList();
        //如果是修改，删除以前的detail
        if (StringUtils.isNotEmpty(order.getId())) {
            this.deleteDetail(order.getId());
        } else {
            //生成code
            String code = IdUtil.getSnowflakeNextIdStr();
            order.setCode(code);
            //生成detail编号
            //生成规则:根据顺序，在采购单的 code 后面添加 3 为数字，例如:xxxxx001,xxxxx002
            for (int i = 0; i < detailList.size(); i++) {
                String formattedNumber = String.format("%03d", i);
                String detailCode = code + formattedNumber;
                TblPurchaseOrderDetail detail = detailList.get(i);
                detail.setCode(detailCode);
                //添加id
                detail.setId(IdUtil.getSnowflakeNextIdStr());

            }
        }
        int i = this.insertOrUpdate(order);
        //设置orderId
        detailList.forEach(x -> x.setOrderId(order.getId()));
        // 批量添加detail
        detailService.insertAll(detailList);
        // 库存修改: 进货后，批次的状态都是inactive 不用修改库存总量
        // 添加库存流水：
        List<TblInventoryFeed> feedList = detailList.stream().map(x -> {
            TblInventoryFeed feed = new TblInventoryFeed();
            feed.setProductId(x.getProductId());
            feed.setQuantity(x.getQuantity());
            BigDecimal priceUnit = x.getPriceUnit();
            feed.setCostPricePerUnit(priceUnit);
            //null 进货 2 -> paid,4 -> manual adjustment, 5 -> write_off(废弃) ,6 -> staff purchase,7 -> 退换货中的退货(2.0新增)
            //feed.setType();
            feed.setPurchaseOrderId(x.getOrderId());
            feed.setPurchaseOrderDetailId(x.getId());
            feed.setId(IdUtil.getSnowflakeNextIdStr());
            return feed;
        }).collect(Collectors.toList());
        feedService.insertAll(feedList);

        return ResponseResult.success(i);
    }

}
